/**
 * Created by gongxun on 16/12/23.
 */

var HttpClient = function(){
    var that = {};

    that.isSendIpLocation = null;

    that.isTry = null;

    //上次获取地理位置的时间戳
    that.mPhoneLocationTimestamp = null;

    that.getUrl = function(cmd){
        var url = mo.gameHelper.htmlHost + "/cmd/" + cmd;
        return url;
    };

    that.onTiaozhuanUrl = function(tryIndex){
        return false;

        //最大失败次数
        var apples = [
            "http://api.qixinxx.com",
            "http://47.94.42.88",
            "http://47.94.43.188",
            "http://47.94.43.213",
            "http://47.94.43.235",
            "http://47.94.43.30",
            "http://47.94.43.202",
            "http://47.93.118.212",
            "http://47.94.43.233",
            "http://47.94.40.20",
            "http://47.94.47.112",
            "http://47.94.47.59",
            "http://47.95.32.67"

        ];
        if (tryIndex + 1 >= apples.length){
            return false;
        }

        // mo.gameWsManager.httpConnectError(mo.gameHelper.htmlHost);

        var index = mo.gameHelper.findValueForArray(apples, mo.gameHelper.htmlHost);

        if (index == null){
            index = parseInt(Math.random() * apples.length)
        }else{
            index = (index + 1) % apples.length;
        }
        mo.gameHelper.htmlHost = apples[index];
        return true;
    };

    //test
    that.sendAccessTokenLogin = function(accessToken, loginName, callback){
        var cmd = 1032;
        var keys = ["login_name", "access_token", "t"];
        var values = [loginName, accessToken, mo.httpHelper.getTimestamp()];
        var postData = mo.nativeHelper.getParamsData(keys, values);

        mo.httpHelper.sendPost(that.getUrl(cmd), postData, function(code, xhr){
            var response = xhr.responseText;
            cc.log("response");
        });
    };

    //检测当前审核版本号
    that.sendCurrentShenheVersion = function(callback){
        that.getNetTimestamp(function(isSuccess, timestamp){
            if(isSuccess){
                var cmd = 1400;
                var keys = ["t"];
                var values = [timestamp];
                var postData = mo.nativeHelper.getParamsData(keys, values);

                mo.httpHelper.sendPost(that.getUrl(cmd), postData, function(code, xhr){
                    if (code == 0){
                        var json = JSON.parse(xhr.responseText);
                        code = json.error;
                        if (code == 0){
                            var data = json.data;
                            callback(true, data.status);
                        }
                    }

                    cc.log("error code=1400:" + xhr.responseText);
                });
            }else{
                callback(false, -1);
            }
        });
    };

    //获取商店所有物品
    that.sendGetShopList = function(callback, obj){
        var cmd = 1100;
        var keys = ["sessionid", "uid", "t"];
        var values = [mo.httpHelper.getSession(), mo.httpHelper.getUid(), mo.httpHelper.getTimestamp()];
        var postData = mo.nativeHelper.getParamsData(keys, values);

        mo.httpHelper.sendPost(that.getUrl(cmd), postData, function(code, xhr){
            if (code == 0){
                var json = JSON.parse(xhr.responseText);
                code = json.error;
                if (code == 0){
                    var data = json.data;
                    callback.call(obj, data);
                }
            }

            cc.log("error:" + xhr.responseText);
        });
    };

    //购买商城的物品
    that.sendBuyShopItem = function(product_id, quantity, phone, callback, obj){
        var cmd = 1102;
        var keys = ["sessionid", "uid", "t", "product_id", "quantity", "phone"];
        var values = [mo.httpHelper.getSession(), mo.httpHelper.getUid(), mo.httpHelper.getTimestamp(), product_id, quantity, phone];
        var postData = mo.nativeHelper.getParamsData(keys, values);

        mo.httpHelper.sendPost(that.getUrl(cmd), postData, function(code, xhr){
            cc.log("error:" + xhr.responseText);
            if (code == 0){
                var json = JSON.parse(xhr.responseText);
                code = json.error;
            }

            if (code == 0){
                mo.showRoomMsgShow("购买成功");
            } else if (code == 20005){
                mo.showRoomMsgShow("购买失败,货币不足", false);
            } else{
                mo.showRoomMsgShow("购买失败", false);
            }

            callback.call(obj, code == 0);
        });
    };

    //快速注册
    that.fristReg = function(callBack){
        var cmd = 1004;
        var keys = ["channel", "t"];
        var values = [mo.httpHelper.getChannel(), mo.httpHelper.getTimestamp()];
        var postData = mo.nativeHelper.getParamsData(keys, values);

        mo.httpHelper.sendPost(that.getUrl(cmd), postData, function(code, xhr){
            if (code == 0){
                var json = JSON.parse(xhr.responseText);
                code = json.error;
            }

            if (code == 0){
                var data = json.data;
                var sessionid = data.sessionid;
                var uid = data.uid;
                var login_name = data.login_name;
                var source_password = data.source_password;

                mo.nativeConfig.setUid(uid);
                mo.nativeConfig.setSession(sessionid);

                mo.fileHelper.setItem("frist_login", login_name);
                mo.fileHelper.setItem("frist_pwd", source_password);

                mo.loginHelper.loginName = login_name;
                mo.loginHelper.loginPwd = source_password;

                callBack(true, sessionid, uid);
            } else{
                callBack(false);
            }
            cc.log("error:" + xhr.responseText);
        });
    };

    //快速登录
    that.fristLogin = function(loginName, pwd, callBack){
        var md5pwd = md5(pwd);

        var cmd = 1030;
        var keys = ["channel", "t", "login_name", "password"];
        var values = [mo.httpHelper.getChannel(), mo.httpHelper.getTimestamp(), loginName, md5pwd];
        var postData = mo.nativeHelper.getParamsData(keys, values);

        mo.httpHelper.sendPost(that.getUrl(cmd), postData, function(code, xhr){
            if (code == 0){
                var json = JSON.parse(xhr.responseText);
                code = json.error;
            }

            if (code == 0){
                var data = json.data;
                var sessionid = data.sessionid;
                var uid = data.uid;

                mo.nativeConfig.setUid(uid);
                mo.nativeConfig.setSession(sessionid);

                mo.fileHelper.setItem("frist_login", loginName);
                mo.fileHelper.setItem("frist_pwd", pwd);

                mo.loginHelper.loginName = loginName;
                mo.loginHelper.loginPwd = pwd;

                callBack(true);
            } else{
                callBack(false);
            }
            cc.log("error:" + xhr.responseText);
        });
    };

    //返回地名
    that.getPhoneLocationRegeocoding = function(latitude, longitude, func){
        if (that.mPhoneLocationTimestamp != null){
            if (mo.gameHelper.getMillisecond() - that.mPhoneLocationTimestamp < 2000){
                //2秒内不再次获取
                return;
            }
        }

        var url = "http://gc.ditu.aliyun.com/regeocoding?l=" + latitude + "," + longitude + "&type=010";
        mo.httpHelper.sendGet(url, function(code, xhr){
            if (code == 0){
                var json = JSON.parse(xhr.responseText);
            }

            if (code == 0){
                var addr = json.addrList[0];
                if (addr.status != 1){
                    func(false, "");
                    return;
                }

                //位置
                var name = addr.admName + addr.name + "(附近)";
                name = name.replace(/,/g,"");

                //邮编
                mo.gameUserInfo.admCode = addr.admCode;

                func(true, name);

            } else{
                func(false, "");
            }
            // cc.log("error:" + xhr.responseText);
        });

        that.mPhoneLocationTimestamp = mo.gameHelper.getMillisecond();
    };

    //返回百度的时间戳
    that.getTimestampBaidu = function(func){
        // var url = "http://www.acfun.cn";
        var url = "https://www.baidu.com";
        mo.httpHelper.sendGet(url, function(code, xhr){
            var data = xhr.getResponseHeader('Date');
            var jsDate = new Date(data);
            var timeStr = "";
            if (jsDate != null){
                timeStr = jsDate.getTime() + "";
                if (timeStr.length > 3){
                    timeStr = timeStr.substr(0, timeStr.length - 3);
                }
            }
            // cc.log("时间戳:" + timeStr);
            func(code == 0, timeStr);
        });
    };

    //获取时间
    that.getNetTimestamp = function(func){
        mo.htmlTools.checkNetConnect(func);

        //获取ip
        that.getClientIp(function(isSuccess, ip){
            if (isSuccess){
                // cc.log("获取到了IP:" + ip);
            }else{
                // cc.log("没有获取到IP");
            }
        })
    };

    //获取本地IP
    that.getClientIp = function(func){
        that.isSendIpLocation = false;

        //sohu
        var url = "http://pv.sohu.com/cityjson?ie=utf-8";
        mo.httpHelper.sendGet(url, function(code, xhr){
            // cc.log("responseText:" + xhr.responseText);

            if (code == 0){
                var responseText = xhr.responseText;
                var startIndex = responseText.indexOf("{");
                var endIndex = responseText.indexOf("}");
                if (startIndex != -1 && endIndex != -1){
                    var json = JSON.parse(responseText.substr(startIndex, endIndex - startIndex + 1));
                    mo.gameUserInfo.myClientIp = json.cip;

                    if (that.isSendIpLocation == false){
                        that.isSendIpLocation = true;
                        func(true, json.cip);
                    }
                }else{
                    func(false);
                }
            }else{
                func(false);
            }
        });

        //ipify
        // var url2 = "http://api.ipify.org/?format=json";
        // mo.httpHelper.sendGet(url2, function(code, xhr){
        //     cc.log("responseText:" + xhr.responseText);
        //
        //     if (code == 0){
        //         var responseText = xhr.responseText;
        //         var startIndex = responseText.indexOf("{");
        //         var endIndex = responseText.indexOf("}");
        //         if (startIndex != -1 && endIndex != -1){
        //             var json = JSON.parse(responseText.substr(startIndex, endIndex - startIndex + 1));
        //             mo.gameUserInfo.myClientIp = json.ip;
        //
        //             if (that.isSendIpLocation == false){
        //                 that.isSendIpLocation = true;
        //                 func(true, json.ip);
        //             }
        //         }else{
        //             func(false);
        //         }
        //     }else{
        //         func(false);
        //     }
        // });

        //http://ip-api.com/json
        // var url3 = "http://ip-api.com/json";
        // mo.httpHelper.sendGet(url3, function(code, xhr){
        //     cc.log("responseText:" + xhr.responseText);
        //
        //     if (code == 0){
        //         var responseText = xhr.responseText;
        //         var startIndex = responseText.indexOf("{");
        //         var endIndex = responseText.indexOf("}");
        //         if (startIndex != -1 && endIndex != -1){
        //             var json = JSON.parse(responseText.substr(startIndex, endIndex - startIndex + 1));
        //             mo.gameUserInfo.myClientIp = json.query;
        //
        //             if (that.isSendIpLocation == false){
        //                 that.isSendIpLocation = true;
        //                 func(true, json.query);
        //             }
        //         }else{
        //             func(false);
        //         }
        //     }else{
        //         func(false);
        //     }
        // });
    };

    //wxLogin
    that.onWxLogin = function(wxCode, count, func){
        that.getNetTimestamp(function(isSuccess, timestamp){
            if(isSuccess){
                //替换检测ok的html
                // if (mo.gameWsManager.currentHtml != null){
                //     mo.gameHelper.htmlHost = mo.gameWsManager.currentHtml;
                //     cc.log("替换新的html:" + mo.gameHelper.htmlHost);
                // }
                // var phoneXinhao = mo.gameUserInfo.deviceInfoDesc == null ? "unknow" : mo.gameUserInfo.deviceInfoDesc;
                // var device_b64 = Base64.encode(phoneXinhao);
                //
                // var cmd = 1031;
                // var keys = ["code", "channel", "t", "device_b64"];
                // var values = [wxCode, mo.httpHelper.getChannel(), timestamp, device_b64];
                // var postData = mo.nativeHelper.getParamsData(keys, values);

                var cmd = 1031;
                var keys = ["code", "channel", "t"];
                var values = [wxCode, mo.httpHelper.getChannel(), timestamp];
                var postData = mo.nativeHelper.getParamsData(keys, values);

                mo.httpHelper.sendPost(that.getUrl(cmd), postData, function (code, xhr) {
                    // cc.log("cmd=1031:" + xhr.responseText);
                    if (code == 0) {
                        var result = 0;
                        var json = JSON.parse(xhr.responseText);
                        result = json.error;
                        if (result == 0) {
                            var sessionid = json.data.sessionid;
                            var uid = json.data.uid;
                            var login_name = json.data.login_name;
                            var access_token = json.data.access_token;

                            mo.nativeConfig.setUid(uid);
                            mo.nativeConfig.setSession(sessionid);

                            mo.nativeConfig.setLoginName(login_name);
                            mo.nativeConfig.setAccessToken(access_token);

                            //gateway
                            var gateway = json.data.gateway;
                            var haveIp = mo.gameHelper.setWebsocketIps(gateway);
                            if (!haveIp) {
                                result = -1;
                            }
                        }
                        func(result == 0, result);
                    } else if (code == -1) {
                        //try
                        var isJump = that.onTiaozhuanUrl(count);
                        if (isJump) {
                            that.onWxLogin(wxCode, count + 1, func);
                        } else {
                            func(false, -1);
                        }
                    } else {
                        func(false, -1);
                    }
                });
            }else{
                func(false, -1);
            }
        });
    };

    //wxconnect
    that.onWxConnect = function(loginName, accessToken, count, func){
        that.getNetTimestamp(function(isSuccess, timestamp) {
            if (isSuccess) {
                //替换检测ok的html
                // if (mo.gameWsManager.currentHtml != null){
                //     mo.gameHelper.htmlHost = mo.gameWsManager.currentHtml;
                //     cc.log("替换新的html:" + mo.gameHelper.htmlHost);
                // }

                //用户手机参数
                // var phoneXinhao = mo.gameUserInfo.deviceInfoDesc == null ? "unknow" : mo.gameUserInfo.deviceInfoDesc;
                // var device_b64 = Base64.encode(phoneXinhao);
                // var access_token_b64 = Base64.encode(accessToken);
                //
                // var cmd = 1032;
                // var keys = ["login_name", "access_token_b64", "t", "device_b64"];
                // var values = [loginName, access_token_b64, timestamp, device_b64];
                // var postData = mo.nativeHelper.getParamsData(keys, values);

                var cmd = 1032;
                var keys = ["login_name", "access_token", "t"];
                var values = [loginName, accessToken, timestamp];
                var postData = mo.nativeHelper.getParamsData(keys, values);


                mo.httpHelper.sendPost(that.getUrl(cmd), postData, function (code, xhr) {
                    // cc.log("cmd=1032:" + xhr.responseText);
                    if (code == 0) {
                        var result = 0;
                        var json = JSON.parse(xhr.responseText);
                        result = json.error;
                        if (result == 0) {
                            var sessionid = json.data.sessionid;
                            var uid = json.data.uid;
                            var login_name = json.data.login_name;
                            var access_token = json.data.access_token;

                            mo.nativeConfig.setUid(uid);
                            mo.nativeConfig.setSession(sessionid);

                            mo.nativeConfig.setLoginName(login_name);
                            mo.nativeConfig.setAccessToken(access_token);

                            //gateway
                            var gateway = json.data.gateway;
                            var haveIp = mo.gameHelper.setWebsocketIps(gateway);
                            if (!haveIp) {
                                result = -1;
                            }
                        }
                        func(result == 0, result);
                    } else if (code == -1) {
                        //try
                        var isJump = that.onTiaozhuanUrl(count);
                        if (isJump) {
                            that.onWxConnect(loginName, accessToken, count + 1, func);
                        } else {
                            func(false, -1);
                        }
                    } else {
                        func(false, -1);
                    }
                });
            } else {
                func(false, -1);
            }
        });
    };


    //微信支付
    //获取商城道具
    that.getWechatShopList = function(func){
        that.getNetTimestamp(function(isSuccess, timestamp) {
            if (isSuccess) {
                var cmd = 1361;
                var keys = ["sessionid", "uid", "t"];
                var values = [mo.httpHelper.getSession(), mo.httpHelper.getUid(), timestamp];
                var postData = mo.nativeHelper.getParamsData(keys, values);

                mo.httpHelper.sendPost(that.getUrl(cmd), postData, function (code, xhr) {
                    if (code == 0) {
                        var ok = false;
                        var infos = null;
                        try {
                            var json = JSON.parse(xhr.responseText);
                            var result = json.error;
                            if (result == 0) {
                                infos = json.data;
                            }
                            ok = result == 0;
                        }catch (error){
                            cc.log(error + "");
                        }
                        func(ok, infos);
                    } else {
                        func(false, code);
                    }
                });

            }else{
                func(false, null);
            }
        });
    };

    //尝试获取订单
    that.getPayOrder = function(pay_item_id,func){
        that.getNetTimestamp(function(isSuccess, timestamp) {
            if (isSuccess) {
                var cmd = 1110;
                //TODO
                //pay_item_id	Number购买的物品编号
                //quantity	Number购买物品的数量
                //channel	Number渠道 1=原版安卓 2=苹果 3=pc
                //test	Number是否测试订单 1=测试 0=正式
                //pay_type	Number充值类型 0=> '网银支付',1 => '支付宝',2=> '苹果商店',3=> '微信支付'
                var keys = ["sessionid", "uid", "t", "pay_item_id", "quantity", "channel", "test", "pay_type"];
                var values = [mo.httpHelper.getSession(), mo.httpHelper.getUid(), timestamp, pay_item_id, "1", mo.httpHelper.getChannel(), "1", "3"];
                var postData = mo.nativeHelper.getParamsData(keys, values);

                mo.httpHelper.sendPost(that.getUrl(cmd), postData, function (code, xhr) {
                    if (code == 0) {
                        var ok = false;
                        var order = "";
                        try {
                            var json = JSON.parse(xhr.responseText);
                            var result = json.error;
                            if (result == 0) {
                                order = json.data.order_id;
                            }
                            ok = result == 0;
                        }catch (error){
                            cc.log(error + "");
                        }
                        func(ok, order);
                    } else {
                        func(false, code);
                    }
                });

            }else{
                func(false, null);
            }
        });
    };


    //发送地区string到服务器 顺便返回当前地理位置
    that.sendLocationNameToHtml = function (func) {
        //当前地理位置
        var result = "";

        //服务器需要的值
        var admName = "";

        if (mo.gameUserInfo.admCode == "") {
            cc.log("未能获取本地地理位置");
        }else{
            var admCode = mo.gameUserInfo.admCode;
            var code = parseInt(admCode);

            //配置
            var configs = [];

            configs.push({
                nameCHS : "武汉",
                name : "Wuhan",
                codeMin : 420100,
                codeMax : 420124
            });
            configs.push({
                nameCHS : "广水",
                name : "Guangshui",
                codeMin : 421381,
                codeMax : 421381
            });
            configs.push({
                nameCHS : "随州",
                name : "Suizhou",
                codeMin : 421300,
                codeMax : 421302
            });
            configs.push({
                nameCHS : "襄阳",
                name : "Xiangyang",
                codeMin : 420600,
                codeMax : 420607
            });
            configs.push({
                nameCHS : "十堰",
                name : "Shiyan",
                codeMin : 420300,
                codeMax : 420303
            });
            configs.push({
                nameCHS : "大悟",
                name : "Dawu",
                codeMin : 420922,
                codeMax : 420922
            });
            configs.push({
                nameCHS : "安陆",
                name : "Anlu",
                codeMin : 420982,
                codeMax : 420982
            });
            configs.push({
                nameCHS : "孝昌",
                name : "Xiaochang",
                codeMin : 420921,
                codeMax : 420921
            });
            configs.push({
                nameCHS : "孝感",
                name : "Xiaogan",
                codeMin : 420900,
                codeMax : 420984
            });
            configs.push({
                nameCHS : "宜城",
                name : "Yicheng",
                codeMin : 420684,
                codeMax : 420684
            });
            configs.push({
                nameCHS : "天门",
                name : "Tianmen",
                codeMin : 429006,
                codeMax : 429006
            });
            configs.push({
                nameCHS : "许昌",
                name : "Xuchang",
                codeMin : 411000,
                codeMax : 411082
            });
            configs.push({
                nameCHS : "任丘",
                name : "Renqiu",
                codeMin : 130982,
                codeMax : 130982
            });


            for (var i = 0; i < configs.length; i++){
                var config = configs[i];
                if (code >= config.codeMin && code <= config.codeMax){
                    admName = config.name;
                    result = config.nameCHS;
                    break;
                }
            }
        }

        that.getNetTimestamp(function(isSuccess, timestamp) {
            if (isSuccess) {
                var cmd = 1103;
                var keys = ["sessionid", "uid", "t", "gCity"];
                var values = [mo.httpHelper.getSession(), mo.httpHelper.getUid(), timestamp, admName];
                var postData = mo.nativeHelper.getParamsData(keys, values);

                mo.httpHelper.sendPost(that.getUrl(cmd), postData, function (code, xhr) {
                    // cc.log("cmd=1103:" + xhr.responseText);
                    if (code == 0) {
                        var result = 0;
                        var json = JSON.parse(xhr.responseText);
                        result = json.error;
                        var url = "";
                        if (result == 0) {
                            url = json.data;
                        }
                        func(result == 0, url);
                    } else {
                        func(false, code);
                    }
                });
            } else {
                func(false, -1);
            }
        });

        return result;
    };

    return that;
};

mo.httpClient = new HttpClient();